import extend from 'extend'
import { modal } from 'vue-strap'
import { showMsg, addPrize, updatePrize } from '../../../../vuex/action'

const validation = {
  miniPrize(data) {
    for (let name in data) {
      if (name === 'type' && data[name] < 0) {
        return false
      }
      if ((data[name] + '').length === 0) {
        return false
      }
    }
    return true
  }
}

export default {
  name: 'mini-prize-config',
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xAddPrize: addPrize,
      xUpdatePrize: updatePrize
    }
  },
  components: {
    'vue-modal': modal
  },
  props: ['title', 'showMiniPrizeModal', 'prize'],
  methods: {
    dipartiteRequest(data) {
      // 更改
      if (this.title === '修改奖品') {
        this.xUpdatePrize(data)
          .then(() => {
            this.showMiniPrizeModal = false
          })
          .catch((res) => {
            this.xShowMsg({
              type: 'danger',
              content: res.error_msg
            })
          })
      } else {
        // 新增
        this.xAddPrize(data)
          .then(() => {
            this.showMiniPrizeModal = false
          })
          .catch((res) => {
            this.xShowMsg({
              type: 'danger',
              content: res.error_msg
            })
          })
      }
    },
    submit() {
      let formData = new FormData()
      let prizeData = extend(true, {}, this.prize)
      let mainData = {
        pic: this.prize.pic || this.prize.picUrl,
        name: this.prize.name,
        totalNum: this.prize.totalNum,
        rate: this.prize.rate
      }
      var valid = validation.miniPrize(mainData)
      if (!valid) {
        return this.xShowMsg({
          type: 'danger',
          content: '* 标记的均为必填/必选项'
        })
      }
      if (+mainData.rate < 0 || +mainData.rate > 1) {
        return this.xShowMsg({
          type: 'danger',
          content: '中奖概率必须在0-1之间'
        })
      }
      prizeData.activityId = +this.prize.activityId
      prizeData.totalNum = +this.prize.totalNum
      prizeData.rate = +this.prize.rate
      prizeData.type = +this.prize.type

      for (let name in prizeData) {
        if (name !== 'picUrl' && name !== 'pic' && name !== 'id') {
          formData.append(name, prizeData[name])
        }
      }
      if (this.title === '修改奖品') {
        formData.append('id', this.prize.id)
      }

      formData.append('pic', this.$els.file.files[0])

      // 请求接口
      this.dipartiteRequest(formData)
    }
  }
}
